home *** CD-ROM | disk | FTP | other *** search
- Path: doc.ic.ac.uk!not-for-mail
- From: njs3@doc.ic.ac.uk (Niall Smart)
- Newsgroups: comp.lang.c
- Subject: Re: revised code of calling a function twice from printf
- Date: 12 Mar 1996 21:28:17 -0000
- Organization: Dept. of Computing, Imperial College, University of London, UK.
- Distribution: world
- Message-ID: <4i4q9h$7pi@oak62.doc.ic.ac.uk>
- References: <4hfs54$k4e@newsbf02.news.aol.com> <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>
- Reply-To: njs3@doc.ic.ac.uk (Niall Smart)
- NNTP-Posting-Host: oak62.doc.ic.ac.uk
- X-Newsreader: mxrn 6.18-23
-
-
- In article <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>, The Amorphous Mass <robinson@blue.weeg.uiowa.edu> writes:
-
- |>> Here is the actual code , modified with everyone's suggestions. However
- |>> there is still a bug in here somewhere. Can anyone please explain what is
- |>> wrong with this.
- |>
- |> You're returning a pointer to an automatic variable, which is
- |>guaranteed bad news.
-
- |>> char *display_drug_type(int drug_index) {
- |>> char drug_type[81]="\0";
- |>
- |> make this
- |> static char drug_type[81]; /* static variables are automatically
- |> initialized to 0, and it's safe to
- |> return their addresses -- they "persist" */
- |>
-
- I beg to differ, this approach is definately *not* safe - subsequent calls
- to display_drug_type will overwrite the memory (drug_type[]) that may be
- referenced by other pointers as shown in this example.
-
- char *pA;
- char *pB;
-
- pA = display_drug_type(iSomeInt);
- pB = display_drug_type(iSomeOtherInt);
-
- now both *pa and *pB are the same, even if iSomeInt != iSomeOtherInt. This
- is because the area of memory that display_drug_type returns is always the
- same. A better solution is to take a char * as an argument or malloc() the
- return.
-
- Niall Smart
- Imperial College London
- njs3@doc.ic.ac.uk
-
-